package com.yiwenup.struct._03_collect.map;

import com.yiwenup.struct._03_collect.map.base.Map;

import java.util.LinkedList;
import java.util.Objects;
import java.util.Queue;

/**
 * 哈希表实现
 **/
@SuppressWarnings("unchecked")
public class HashMap<K, V> implements Map<K, V> {
    private int size;
    private Node<K, V>[] table;

    public static final int DEFAULT_CAPACITY = 1 << 4;
    /**
     * 装填因子 = 节点数量 / 桶数量
     */
    public static final float DEFAULT_LOAD_FACTOR = 0.75F;

    public HashMap() {
        table = new Node[DEFAULT_CAPACITY];
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public void clear() {
        if (size == 0) return;
        for (int i = 0; i < table.length; i++) {
            table[i] = null;
        }
        size = 0;
    }

    @Override
    public V put(K key, V value) {
        resize();
        int index = index(key);
        Node<K, V> root = table[index];
        if (root == null) {
            root = createNode(key, value, null);
            table[index] = root;
            size++;
            fixRBTreeAfterPut(root);
            return null;
        }
        // 添加新节点
        Node<K, V> parent = root;
        Node<K, V> node = root;
        int compare = 0;
        K k1 = key;
        int h1 = hash(k1);
        Node<K, V> res = null;
        // 是否已经搜索过该key了
        boolean searched = false;
        do {
//            compare = compare(key, h1, node.key, node.hash);
            parent = node;
            K k2 = node.key;
            int h2 = node.hash;
            if (h1 > h2) {
                compare = 1;
            } else if (h1 < h2) {
                compare = -1;
            } else if (Objects.equals(k1, k2)) {
                compare = 0;
            } else if (k1 != null
                    && k2 != null
                    && k1 instanceof Comparable
                    && k1.getClass() == k2.getClass()
                    && (compare = ((Comparable) k1).compareTo(k2)) != 0) {

            } else if (searched) {
                compare = System.identityHashCode(k1) - System.identityHashCode(k2);
            } else {
                if ((node.left != null && (res = node(node.left, k1)) != null)
                        || (node.right != null && (res = node(node.right, k1)) != null)) {
                    node = res;
                    compare = 0;
                } else {
                    searched = true;
                    compare = System.identityHashCode(k1) - System.identityHashCode(k2);
                }
            }

            if (compare > 0) {
                node = node.right;
            } else if (compare < 0) {
                node = node.left;
            } else {
                node.key = key;
                V oldValue = node.value;
                node.value = value;
                node.hash = h1;
                return oldValue;
            }
        } while (node != null);

        //
        Node<K, V> newNode = createNode(key, value, parent);
        if (compare > 0) {
            parent.right = newNode;
        } else {
            parent.left = newNode;
        }
        size++;
        fixRBTreeAfterPut(newNode);
        return null;
    }

    protected Node<K,V> createNode(K key, V value, Node<K, V> parent) {
        return new Node<>(key, value, parent);
    }

    private void resize() {
        if (size / table.length <= DEFAULT_LOAD_FACTOR) return;

        Node<K, V>[] bak = table;
        table = new Node[bak.length << 1];
        size = 0;

        Queue<Node<K, V>> queue = new LinkedList<>();
        for (int i = 0; i < bak.length; i++) {
            if (bak[i] == null) continue;

            queue.offer(bak[i]);
            while (!queue.isEmpty()) {
                Node<K, V> node = queue.poll();
                if (node.left != null) queue.offer(node.left);
                if (node.right != null) queue.offer(node.right);
                moveNode(node);
            }
        }
    }

    private void moveNode(Node<K, V> newNode) {
        // 重置
        newNode.parent = null;
        newNode.left = null;
        newNode.right = null;
        newNode.color = RED;

        int index = index(newNode);
        Node<K, V> root = table[index];
        if (root == null) {
            root = newNode;
            table[index] = root;
            fixRBTreeAfterPut(root);
            return;
        }
        // 添加新节点
        Node<K, V> parent = root;
        Node<K, V> node = root;
        int compare = 0;
        K k1 = newNode.key;
        int h1 = newNode.hash;
        do {
            parent = node;
            K k2 = node.key;
            int h2 = node.hash;
            if (h1 > h2) {
                compare = 1;
            } else if (h1 < h2) {
                compare = -1;
            } else if (k1 != null
                    && k2 != null
                    && k1 instanceof Comparable
                    && k1.getClass() == k2.getClass()
                    && (compare = ((Comparable) k1).compareTo(k2)) != 0) {

            } else {
                compare = System.identityHashCode(k1) - System.identityHashCode(k2);
            }

            if (compare > 0) {
                node = node.right;
            } else if (compare < 0) {
                node = node.left;
            }
        } while (node != null);

        newNode.parent = parent;
        if (compare > 0) {
            parent.right = newNode;
        } else {
            parent.left = newNode;
        }
        fixRBTreeAfterPut(newNode);
    }

    @Deprecated
    private int compare(K k1, int h1, K k2, int h2) {
        // 判断放在当前节点的左边还是右边
        // 比较哈希值
        int res = h1 - h2;
        if (res != 0) return res;

        // 比较equals
        if (Objects.equals(k1, k2)) return 0;

        // 比较类名
        if (k1 != null && k2 != null) {
            String clz1 = k1.getClass().getName();
            String clz2 = k2.getClass().getName();
            res = clz1.compareTo(clz2);
            if (res != 0) return res;

            // 同一种类型且具备可比较性
            if (k1 instanceof Comparable) {
                return ((Comparable) k1).compareTo(k2);
            }
        }

        // 同种类型但是不具备比较性
        // 两者有其一为空另一个不为空
        return System.identityHashCode(k1) - System.identityHashCode(k2);
    }

    private void fixRBTreeAfterPut(Node<K, V> node) {
        Node<K, V> parent = node.parent;
        // 添加的是根节点，或者上溢到了根节点
        if (parent == null) {
            black(node);
            return;
        }

        // 如果父节点是黑色则返回
        if (isBlack(parent)) return;

        // 叔父节点
        Node<K, V> uncle = parent.sibling();
        // 祖父节点
        Node<K, V> grand = parent.parent;
        if (isRed(uncle)) {
            black(parent);
            black(uncle);
            // 将祖父节点当作新添加的节点上溢
            fixRBTreeAfterPut(red(grand));
            return;
        }

        // 叔父节点不是红色的
        if (parent.isLeftChild()) {
            red(grand);
            if (node.isLeftChild()) {
                // LL
                black(parent);
            } else {
                // LR
                black(node);
                rotateLeft(parent);
            }
            rotateRight(grand);
        } else {
            red(grand);
            if (node.isRightChild()) {
                // RR
                black(parent);
            } else {
                // RL
                black(node);
                rotateRight(parent);
            }
            rotateLeft(grand);
        }
    }

    private int index(K key) {
        return hash(key) & (table.length - 1);
    }

    private int index(Node<K, V> node) {
        // 是用位运算要求table大小为2的n次方
        return node.hash & (table.length - 1);
    }

    private int hash(K key) {
        if (key == null) return 0;
        int hash = key.hashCode();
        return hash ^ (hash >>> 16);
    }

    @Override
    public V get(K key) {
        Node<K, V> node = node(key);
        return node != null ? node.value : null;
    }

    private Node<K, V> node(K key) {
        Node<K, V> root = table[index(key)];
        return root == null ? null : node(root, key);
    }

    private Node<K, V> node(Node<K, V> node, K k1) {
        int h1 = hash(k1);
        Node<K, V> res = null;
        int compare = 0;

        while (node != null) {
            K k2 = node.key;
            int h2 = node.hash;
            if (h1 > h2) {
                node = node.right;
            } else if (h1 < h2) {
                node = node.left;
            } else if (Objects.equals(k1, k2)) {
                return node;
            } else if (k1 != null
                    && k2 != null
                    && k1 instanceof Comparable
                    && k1.getClass() == k2.getClass()
                    && (compare = ((Comparable) k1).compareTo(k2)) != 0) {
                node = compare > 0 ? node.right : node.left;
            } else if (node.right != null && (res = node(node.right, k1)) != null) {
                return res;
            } else {
                node = node.left;
            }
        }
        return null;
    }

    @Override
    public V remove(K key) {
        return remove(node(key));
    }

    protected V remove(Node<K, V> node) {
        if (node == null) return null;

        Node<K, V> pointNode = node;

        V oldValue = node.value;

        if (node.hasTwoChildren()) {
            // 度为2
            Node<K, V> successor = successor(node);
            // 后继节点的值覆盖度为2的值
            node.key = successor.key;
            node.value = successor.value;
            node.hash = successor.hash;
            // 删除后继节点
            node = successor;
        }

        // 删除度为1或0的节点
        Node<K, V> replace = node.left != null ? node.left : node.right;

        int index = index(node);
        if (replace != null) {
            // 度为1
            replace.parent = node.parent;
            if (node.parent == null) {
                // 度为1，且是根节点
                table[index] = replace;
            } else if (node == node.parent.left) {
                node.parent.left = replace;
            } else {
                node.parent.right = replace;
            }

            fixRBTreeAfterRemove(replace);
        } else if (node.parent == null) {
            // 度为0，且是根节点
            table[index] = null;
            fixRBTreeAfterRemove(node);
        } else {
            // 度为0，但不是根节点 -> 叶子节点
            if (node.parent.left == node) {
                node.parent.left = null;
            } else {
                node.parent.right = null;
            }
            fixRBTreeAfterRemove(node);
        }

        // 交给子类去实现
        afterRemove(pointNode, node);

        size--;

        return oldValue;
    }

    protected void afterRemove(Node<K,V> pointNode, Node<K, V> replaceNode) {
    }

    private Node<K, V> successor(Node<K, V> node) {
        if (node == null) return null;

        // 前驱节点在左子树中 node.right.left.left.left....
        Node<K, V> pre = node.right;
        if (pre != null) {
            while (pre.left != null) {
                pre = pre.left;
            }
            return pre;
        }

        // 从父节点中寻找前驱节点
        while (node.parent != null && node == node.parent.right) {
            node = node.parent;
        }

        return node.parent;
    }

    private void fixRBTreeAfterRemove(Node<K, V> node) {
        if (isRed(node)) {
            // 如果删除的节点是红色，则直接删除
            // 或者将要取代被删除节点位置的节点，如果是红色
            black(node);
            return;
        }

        // 删除的是叶子
        Node<K, V> parent = node.parent;
        if (parent == null) return;

        // 下溢
        boolean wasLeft = parent.left == null || node.isLeftChild();
        Node<K, V> sibling = wasLeft ? parent.right : parent.left;
        if (wasLeft) {
            // 被删除的节点在左边
            if (isRed(sibling)) {
                // 如果兄弟节点是红色，则通过旋转将情况变成兄弟节点是黑色的情况
                black(sibling);
                red(parent);
                rotateLeft(parent);
                // 重新赋值兄弟
                sibling = parent.right;
            }

            // 兄弟节点是黑色
            if (isBlack(sibling.left) && isBlack(sibling.right)) {
                boolean parentBlack = isBlack(parent);
                black(parent);
                red(sibling);
                if (parentBlack) {
                    fixRBTreeAfterRemove(parent);
                }
            } else {
                // 兄弟节点至少有一个红色子节点
                if (isBlack(sibling.right)) {
                    rotateRight(sibling);
                    sibling = parent.right;
                }

                color(sibling, colorOf(parent));
                black(sibling.right);
                black(parent);

                rotateLeft(parent);
            }
        } else {
            // 被删除的节点在右边
            if (isRed(sibling)) {
                // 如果兄弟节点是红色，则通过旋转将情况变成兄弟节点是黑色的情况
                black(sibling);
                red(parent);
                rotateRight(parent);
                // 重新赋值兄弟
                sibling = parent.left;
            }

            // 兄弟节点是黑色
            if (isBlack(sibling.left) && isBlack(sibling.right)) {
                boolean parentBlack = isBlack(parent);
                black(parent);
                red(sibling);
                if (parentBlack) {
                    fixRBTreeAfterRemove(parent);
                }
            } else {
                // 兄弟节点至少有一个红色子节点
                if (isBlack(sibling.left)) {
                    rotateLeft(sibling);
                    sibling = parent.left;
                }

                color(sibling, colorOf(parent));
                black(sibling.left);
                black(parent);

                rotateRight(parent);
            }
        }
    }


    private void rotateLeft(Node<K, V> g) {
        Node<K, V> p = g.right;
        Node<K, V> t1 = p.left;
        g.right = t1;
        p.left = g;

        afterRotate(g, p, t1);
    }

    private void rotateRight(Node<K, V> g) {
        Node<K, V> p = g.left;
        Node<K, V> t2 = p.right;
        g.left = t2;
        p.right = g;

        afterRotate(g, p, t2);
    }

    private void afterRotate(Node<K, V> g, Node<K, V> p, Node<K, V> t) {
        // 使P成为子树的根节点
        p.parent = g.parent;
        if (g.isLeftChild()) {
            g.parent.left = p;
        } else if (g.isRightChild()) {
            g.parent.right = p;
        } else {
            // g就是整棵树的根节点
            table[index(g)] = p;
        }

        // 使子树的父节点是之前的根节点
        if (t != null) {
            t.parent = g;
        }

        // 使之前根节点的父节点是新的根节点
        g.parent = p;

        // 高度更新
    }

    private boolean isBlack(Node<K, V> node) {
        return colorOf(node) == BLACK;
    }

    private boolean isRed(Node<K, V> node) {
        return colorOf(node) == RED;
    }

    private boolean colorOf(Node<K, V> node) {
        return node == null ? BLACK : node.color;
    }

    private Node<K, V> red(Node<K, V> node) {
        return color(node, RED);
    }

    private Node<K, V> black(Node<K, V> node) {
        return color(node, BLACK);
    }

    /**
     * 染色
     *
     * @param node  染色节点
     * @param color 颜色
     * @return 染色节点
     */
    private Node<K, V> color(Node<K, V> node, boolean color) {
        if (node == null) return null;
        node.color = color;
        return node;
    }

    @Override
    public boolean containsKey(K key) {
        return node(key) != null;
    }

    @Override
    public boolean containsValue(V value) {
        if (size == 0) return false;
        Queue<Node<K, V>> queue = new LinkedList<>();
        for (int i = 0; i < table.length; i++) {
            if (table[i] == null) continue;

            queue.offer(table[i]);
            while (!queue.isEmpty()) {
                Node<K, V> node = queue.poll();
                if (Objects.equals(node.value, value)) return true;
                if (node.left != null) queue.offer(node.left);
                if (node.right != null) queue.offer(node.right);
            }
        }
        return false;
    }

    @Override
    public void traversal(Visitor<K, V> visitor) {
        if (size == 0 || visitor == null) return;
        Queue<Node<K, V>> queue = new LinkedList<>();
        for (int i = 0; i < table.length; i++) {
            if (table[i] == null) continue;

            queue.offer(table[i]);
            while (!queue.isEmpty()) {
                Node<K, V> node = queue.poll();
                if (visitor.visit(node.key, node.value)) return;
                if (node.left != null) queue.offer(node.left);
                if (node.right != null) queue.offer(node.right);
            }
        }
    }

    public static final boolean RED = false;
    public static final boolean BLACK = true;

    protected static class Node<K, V> {
        boolean color = RED;
        K key;
        V value;
        int hash;
        Node<K, V> left;
        Node<K, V> right;
        Node<K, V> parent;

        public Node(K key, V value, Node<K, V> parent) {
            this.key = key;
            this.value = value;
            int hash = key == null ? 0 : key.hashCode();
            this.hash = hash ^ (hash >>> 16);
            this.parent = parent;
        }

        public boolean isLeaf() {
            return left == null && right == null;
        }

        public boolean hasTwoChildren() {
            return left != null && right != null;
        }

        public boolean isLeftChild() {
            return parent != null && this == parent.left;
        }

        public boolean isRightChild() {
            return parent != null && this == parent.right;
        }

        public Node<K, V> sibling() {
            if (isLeftChild()) {
                return parent.right;
            }
            if (isRightChild()) {
                return parent.left;
            }
            return null;
        }
    }
}
